﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using CPlatePrintSys.Annotation.Events;
using CPlatePrintSys.Application.Views;
using CPlatePrintSys.Application.Services;
using CPlatePrintSys.Domain.Events;
using CPlatePrintSys.Domain.DTOs;
using CPlatePrintSys.Infrastructure;
using CPlatePrintSys.Infrastructure.Models;
using CPlatePrintSys.Win.Events;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Navigation;
using Prism.Navigation.Regions;
using CPlatePrintSys.Domain.Models;
using CPlatePrintSys.Infrastructure.Repositories;
using CPlatePrintSys.Application.ViewModels;
using CPlatePrintSys.Domain.Services;
using CPlatePrintSys.Win.Views;
using CPlatePrintSys.Win.Controls;
using CPlatePrintSys.Annotation.Models;
using CPlatePrintSys.Annotation;
using Org.BouncyCastle.Pqc.Crypto.Lms;
using System.IO;

namespace CPlatePrintSys.Win.ViewModels
{
    public class ProcessSequenceViewModel : BindableBase, INavigationAware
    {
        private readonly IEventAggregator _eventAggregator;
        private readonly IRegionManager _regionManager;

        // 导航参数
        private int _workSpaceId;
        public int WorkSpaceId
        {
            get => _workSpaceId;
            set => SetProperty(ref _workSpaceId, value);
        }

        private string _workSpaceName = string.Empty;
        public string WorkSpaceName
        {
            get => _workSpaceName;
            set => SetProperty(ref _workSpaceName, value);
        }

        private string _subTitle = string.Empty;
        public string SubTitle
        {
            get { return _subTitle; }
            set { SetProperty(ref _subTitle, value); }
        }

        public ICommand BackToHomeCommand { get; }

        // 查询条件属性
        private string _selectedStreamShipNo = "全部";
        public string SelectedStreamShipNo { get => _selectedStreamShipNo; set => SetProperty(ref _selectedStreamShipNo, value); }
        private string _selectedLotNo = "全部";
        public string SelectedLotNo { get => _selectedLotNo; set => SetProperty(ref _selectedLotNo, value); }
        private string _selectedSequence = "全部";
        public string SelectedSequence { get => _selectedSequence; set => SetProperty(ref _selectedSequence, value); }
        private DateTime? _selectedPlanUsedDateStart;
        public DateTime? SelectedPlanUsedDateStart { get => _selectedPlanUsedDateStart; set => SetProperty(ref _selectedPlanUsedDateStart, value); }
        private DateTime? _selectedPlanUsedDateEnd;
        public DateTime? SelectedPlanUsedDateEnd { get => _selectedPlanUsedDateEnd; set => SetProperty(ref _selectedPlanUsedDateEnd, value); }
        private string _selectedAnnotationStatus = "全部";
        public string SelectedAnnotationStatus { get => _selectedAnnotationStatus; set => SetProperty(ref _selectedAnnotationStatus, value); }

        // 查询进度条
        private bool _isQuerying = false;
        public bool IsQuerying { get => _isQuerying; set => SetProperty(ref _isQuerying, value); }

        // 筛选后集合
        private ObservableCollection<PlateAnnotationInfoViewModel> _filteredPlateAnnotationInfos = new ObservableCollection<PlateAnnotationInfoViewModel>();
        public ObservableCollection<PlateAnnotationInfoViewModel> FilteredPlateAnnotationInfos
        {
            get => _filteredPlateAnnotationInfos;
            set
            {
                // 取消之前集合的事件订阅
                if (_filteredPlateAnnotationInfos != null)
                {
                    foreach (var item in _filteredPlateAnnotationInfos)
                    {
                        item.SelectionChanged -= OnItemSelectionChanged;
                    }
                }

                SetProperty(ref _filteredPlateAnnotationInfos, value);

                // 订阅新集合的事件
                if (_filteredPlateAnnotationInfos != null)
                {
                    foreach (var item in _filteredPlateAnnotationInfos)
                    {
                        item.SelectionChanged += OnItemSelectionChanged;
                    }
                }

                // 创建合并数据
                CreateMergedData();

                // 更新全选状态
                UpdateSelectAllState();
                
                // 重新评估标注命令的可执行状态
                AnnotationCommand?.RaiseCanExecuteChanged();

                // 重新评估导出图纸命令的可执行状态
                ExportDocumentsCommand?.RaiseCanExecuteChanged();

                //重新评估合并布局命令的可执行状态
                MergeLayoutCommand?.RaiseCanExecuteChanged();
            }
        }

        // 合并后的数据集合
        private ObservableCollection<MergedPlateAnnotationInfoViewModel> _mergedPlateAnnotationInfos = new ObservableCollection<MergedPlateAnnotationInfoViewModel>();
        public ObservableCollection<MergedPlateAnnotationInfoViewModel> MergedPlateAnnotationInfos
        {
            get => _mergedPlateAnnotationInfos;
            set => SetProperty(ref _mergedPlateAnnotationInfos, value);
        }

        // 全选相关属性
        private bool _isAllSelected = false;
        public bool IsAllSelected
        {
            get => _isAllSelected;
            set => SetProperty(ref _isAllSelected, value);
        }

        // 批量操作标志，防止在批量设置时触发单行选择状态改变事件
        private bool _isBatchSelecting = false;

        // 当前选中的项（用于标注按钮）
        private PlateAnnotationInfoViewModel _currentSelectedItem;
        public PlateAnnotationInfoViewModel CurrentSelectedItem
        {
            get => _currentSelectedItem;
            set 
            {
                if (SetProperty(ref _currentSelectedItem, value))
                {
                    // 当选中项改变时，重新评估命令的可执行状态
                    AnnotationCommand?.RaiseCanExecuteChanged();
                }
            }
        }

        // 当前选中的合并项
        private MergedPlateAnnotationInfoViewModel _currentSelectedMergedItem;
        public MergedPlateAnnotationInfoViewModel CurrentSelectedMergedItem
        {
            get => _currentSelectedMergedItem;
            set 
            {
                if (SetProperty(ref _currentSelectedMergedItem, value))
                {
                    // 当选中项改变时，重新评估命令的可执行状态
                    AnnotationCommand?.RaiseCanExecuteChanged();
                    ExportDocumentsCommand?.RaiseCanExecuteChanged();
                    MergeLayoutCommand?.RaiseCanExecuteChanged();
                }
            }
        }

        // 查询命令
        public DelegateCommand SearchCommand { get; set; }
        public DelegateCommand ResetCommand { get; set; }
        public DelegateCommand SelectAllCommand { get; set; }

        public DelegateCommand BuildWorkSpaceCommand { get; set; }

        // 输出图纸命令
        public DelegateCommand ExportDocumentsCommand { get; set; }

        // 标注命令
        public DelegateCommand AnnotationCommand { get; set; }

        public ProcessSequenceViewModel(IRegionManager regionManager, IEventAggregator eventAggregator, ShipInfoService shipInfoService, ILayoutService layoutService, IWorkSpaceService workSpaceService, IGlobalConfigService globalConfigService, DataSyncService dataSyncService)
        {
            _regionManager = regionManager;
            _eventAggregator = eventAggregator;
            _shipInfoService = shipInfoService;
            _layoutService = layoutService;
            _workSpaceService = workSpaceService;
            _globalConfigService = globalConfigService;
            _dataSyncService = dataSyncService;

            _subTitle = "工作空间";

            BackToHomeCommand = new DelegateCommand(BackToHome);

            // 初始化KmacsService（此处可后续支持注入或配置API地址）
            _kmacsService = new KmacsService();

            RefreshKmacsCommand = new DelegateCommand(async () => await SyncAndMergeAllSourcesAsync());

            // 多来源命令（保留但不暴露给UI）
            LoadKmacsCommand = new DelegateCommand(async () => await LoadKmacsPlateAnnotationInfosAsync());
            LoadAmCommand = new DelegateCommand(async () => await LoadAmPlateAnnotationInfosAsync());
            LoadCadWinCommand = new DelegateCommand(async () => await LoadCadWinPlateAnnotationInfosAsync());

            MoundCommand();

            SearchCommand = new DelegateCommand(async () => await ApplyFilterAsync());
            ResetCommand = new DelegateCommand(ResetFilter);
            SelectAllCommand = new DelegateCommand(ExecuteSelectAll, CanExecuteSelectAll);

            // 布局相关命令
            MergeLayoutCommand = new DelegateCommand(async () => await ExecuteMergeLayoutAsync(), CanMergeLayout);
            AutoMirrorLayoutCommand = new DelegateCommand(async () => await ExecuteAutoMirrorLayoutAsync());

            // 输出图纸命令
            ExportDocumentsCommand = new DelegateCommand(ExecuteExportDocuments, CanExecuteExportDocuments);

            // 标注命令
            AnnotationCommand = new DelegateCommand(ExecuteAnnotation, CanExecuteAnnotation);

            BuildWorkSpaceCommand = new DelegateCommand(AddBaseInfo);

            // 工作空间相关命令
            RefreshWorkSpaceCommand = new DelegateCommand(async () => await RefreshWorkSpaceAsync());
            EditWorkSpaceCommand = new DelegateCommand(EditWorkSpace);

            // 初始化工作空间树
            //workspaceTree = new ObservableCollection<BaseInfoTreeNode>();
            WorkSpaceNodes = new ObservableCollection<BaseInfoTreeNode>();

            // 初始化工作空间
            InitializeWorkSpaceAsync();

            // 加载测试数据用于布局功能验证
            //LoadTestData();
            
            // 临时启用合并测试数据（用于测试合并功能）
            //LoadMergeTestData();

            // 订阅布局信息更新领域事件
            this._eventAggregator.GetEvent<LayoutInfoUpdatedEvent>().Subscribe(OnLayoutInfoUpdated);

            // 订阅解除合并布局领域事件
            this._eventAggregator.GetEvent<UnmergeLayoutEvent>().Subscribe(OnUnmergeLayout);

            this._eventAggregator.GetEvent<SaveAnnotationEvent>().Subscribe(OnSaveAnnotation);
        }


        private async void OnSaveAnnotation(string docName)
        {
            try
            {
                // 获取当前编辑的标注信息
                var annotationManager = CPlatePrintSys.Annotation.AnnotationManager.Instance;
                var currentEditInfo = annotationManager.CurrentEditAnnotationInfo;
                
                if (currentEditInfo == null)
                {
                    System.Diagnostics.Debug.WriteLine("当前没有编辑的标注信息，无法保存");
                    MessageBox.Show("当前没有编辑的标注信息，无法保存", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                
                // 获取需要更新的记录
                var toSaveItems = new List<PlateAnnotationInfoViewModel>();
                
                // 如果是合并图纸，需要更新所有相关的图纸
                if (currentEditInfo.LayoutMean == LayoutMean.MergedLayout && !string.IsNullOrEmpty(currentEditInfo.LayoutInfo))
                {
                    try
                    {
                        // 解析LayoutInfo获取所有相关的SheetConsistentNo
                        var layoutInfo = JsonConvert.DeserializeObject<LayoutInfo>(currentEditInfo.LayoutInfo);
                        if (layoutInfo?.Merged?.PartLayouts != null && layoutInfo.Merged.PartLayouts.Any())
                        {
                            var mergedSheetConsistentNos = layoutInfo.Merged.PartLayouts.Select(p => p.SheetConsistentNo).ToHashSet();
                            toSaveItems = FilteredPlateAnnotationInfos.Where(x => mergedSheetConsistentNos.Contains(x.OriginalData.SheetConsistentNo)).ToList();
                            System.Diagnostics.Debug.WriteLine($"合并图纸标注保存，找到 {toSaveItems.Count} 条相关记录");
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"解析LayoutInfo失败: {ex.Message}");
                    }
                }
                
                // 如果没有找到合并相关的记录，则只更新当前编辑的记录
                if (!toSaveItems.Any())
                {
                    toSaveItems = FilteredPlateAnnotationInfos.Where(x => x.OriginalData.Id == currentEditInfo.Id).ToList();
                    System.Diagnostics.Debug.WriteLine($"非合并图纸标注保存，更新当前记录");
                }
                
                if (toSaveItems != null && toSaveItems.Any())
                {
                    var idsToUpdate = toSaveItems.Select(x => x.OriginalData.Id).ToList();
                    
                    // 通过DataSyncService更新数据库中的标注生成状态
                    await _dataSyncService.UpdateAnnotationGeneratedStatusAsync(idsToUpdate, true);
                    
                    // 更新内存中的数据状态
                    foreach (var item in toSaveItems)
                    {
                        item.OriginalData.IsAnnotationGenerated = true;
                    }
                    
                    // 刷新合并数据以更新UI状态
                    CreateMergedData();
                    
                    // 重新评估命令状态
                    ExportDocumentsCommand?.RaiseCanExecuteChanged();
                    AnnotationCommand?.RaiseCanExecuteChanged();
                    MergeLayoutCommand?.RaiseCanExecuteChanged();
                    
                    System.Diagnostics.Debug.WriteLine($"已更新标注状态，记录ID: {currentEditInfo.Id}, 钢板一贯编号: {currentEditInfo.SheetConsistentNo}, 更新了 {toSaveItems.Count} 条记录");
                    
                    // 显示保存成功提示
                    MessageBox.Show($"标注信息保存成功！", "保存成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"未找到要更新的记录，ID: {currentEditInfo.Id}");
                    MessageBox.Show("未找到要更新的记录，保存失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                //返回主界面
                _regionManager.RequestNavigate(ConstStrings.UI_Region_Main_Content, "MainWindow");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存标注信息失败: {ex.Message}");
                MessageBox.Show($"保存标注信息失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BackToHome()
        {
            _regionManager.RequestNavigate(ConstStrings.UI_Region_Secondary_Content, "HomeView");
        }

        private async Task LoadKmacsProcessInfosAsync()
        {
            var list = await _kmacsService.GetProcessInfosAsync();
            KmacsProcessInfos = new ObservableCollection<KmacsProcessInfoDto>(list);
        }

        private async void InitializeWorkSpaceAsync()
        {
            try
            {
                // 尝试从本地配置加载工作空间
                var workSpace = await _workSpaceService.LoadWorkSpaceFromLocalConfigAsync();
                if (workSpace != null)
                {
                    _workSpaceService.SetCurrentWorkSpace(workSpace);
                    LoadWorkSpaceNodes(workSpace.WorkSpaceNodes);
                }
                else
                {
                    // 如果没有保存的工作空间，创建空的工作空间
                    var emptyWorkSpace = new WorkSpace
                    {
                        Name = "默认工作空间",
                        Description = "系统默认工作空间",
                        WorkSpaceNodes = new List<WorkSpaceNode>()
                    };
                    _workSpaceService.SetCurrentWorkSpace(emptyWorkSpace);
                    LoadWorkSpaceNodes(new List<WorkSpaceNode>());
                }
            }
            catch (Exception ex)
            {
                // 如果加载失败，创建空的工作空间
                var emptyWorkSpace = new WorkSpace
                {
                    Name = "默认工作空间",
                    Description = "系统默认工作空间",
                    WorkSpaceNodes = new List<WorkSpaceNode>()
                };
                _workSpaceService.SetCurrentWorkSpace(emptyWorkSpace);
                LoadWorkSpaceNodes(new List<WorkSpaceNode>());
            }
        }

        private void LoadWorkSpaceNodes(List<WorkSpaceNode> nodes)
        {
            // 将WorkSpaceNode转换为BaseInfoTreeNode
            var baseInfoNodes = new ObservableCollection<BaseInfoTreeNode>();

            foreach (var node in nodes)
            {
                var baseInfoNode = ConvertWorkSpaceNodeToBaseInfoNode(node, null);
                if (baseInfoNode != null)
                {
                    baseInfoNodes.Add(baseInfoNode);
                }
            }

            // 更新工作空间树控件
            if (WorkSpaceNodes != null)
            {
                WorkSpaceNodes.Clear();
                foreach (var node in baseInfoNodes)
                {
                    WorkSpaceNodes.Add(node);
                }
            }

            // 调试信息：打印树形结构
            System.Diagnostics.Debug.WriteLine($"ProcessSequenceView - 加载的工作空间节点数量: {baseInfoNodes.Count}");
            foreach (var node in baseInfoNodes)
            {
                PrintBaseInfoNodeHierarchy(node, 0);
            }
        }

        private BaseInfoTreeNode ConvertWorkSpaceNodeToBaseInfoNode(WorkSpaceNode workSpaceNode, BaseInfoTreeNode parentNode)
        {
            if (workSpaceNode == null) return null;

            var baseInfoNode = new BaseInfoTreeNode(workSpaceNode.Name, parentNode);

            // 递归处理子节点
            if (workSpaceNode.Children != null && workSpaceNode.Children.Any())
            {
                foreach (var child in workSpaceNode.Children)
                {
                    var childBaseInfoNode = ConvertWorkSpaceNodeToBaseInfoNode(child, baseInfoNode);
                    if (childBaseInfoNode != null)
                    {
                        baseInfoNode.Children.Add(childBaseInfoNode);
                    }
                }
            }

            return baseInfoNode;
        }

        private void PrintBaseInfoNodeHierarchy(BaseInfoTreeNode node, int level)
        {
            var indent = new string(' ', level * 2);
            System.Diagnostics.Debug.WriteLine($"{indent}Name: {node.Name}, Children: {node.Children?.Count ?? 0}");

            if (node.Children != null)
            {
                foreach (var child in node.Children)
                {
                    PrintBaseInfoNodeHierarchy(child, level + 1);
                }
            }
        }

        private async void AddBaseInfo()
        {
            try
            {
                var vm = new AddBaseInfoViewModel(_workSpaceService, _eventAggregator);
                var dialog = new AddBaseInfoView();
                dialog.DataContext = vm;
                dialog.Owner = System.Windows.Application.Current.MainWindow;
                dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                var result = dialog.ShowDialog();
                if (result == true)
                {
                    // 工作空间创建成功，刷新工作空间
                    await RefreshWorkSpaceAsync();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建工作空间失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task RefreshWorkSpaceAsync()
        {
            try
            {
                var currentWorkSpace = _workSpaceService.GetCurrentWorkSpace();
                if (currentWorkSpace != null)
                {
                    // 设置WorkSpaceId，这样LoadProcessSequenceDataAsync就能正确过滤
                    WorkSpaceId = currentWorkSpace.Id;
                    WorkSpaceName = currentWorkSpace.Name;
                    
                    System.Diagnostics.Debug.WriteLine($"刷新工作空间，WorkSpaceId: {WorkSpaceId}, WorkSpaceName: {WorkSpaceName}");
                    
                    // 使用统一的数据加载流程
                    _ = LoadProcessSequenceDataAsync();
                }
                else
                {
                    // 如果没有当前工作空间，清空数据
                    WorkSpaceId = 0;
                    WorkSpaceName = string.Empty;
                    WorkSpaceNodes?.Clear();
                    PlateAnnotationInfos?.Clear();
                    FilteredPlateAnnotationInfos?.Clear();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"刷新工作空间失败: {ex.Message}");
                MessageBox.Show($"刷新工作空间失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }


        /// <summary>
        /// 统一的ProcessSequenceView数据加载流程
        /// 1. 从数据库查询所有PlateAnnotationInfo
        /// 2. 根据工作空间节点进行过滤（使用OR关系，更灵活）
        /// 3. 更新UI显示
        /// </summary>
        private async Task LoadProcessSequenceDataAsync()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("开始加载ProcessSequenceView数据...");
                
                // 步骤1：从数据库查询所有PlateAnnotationInfo
                var allPlateAnnotationInfos = await _dataSyncService.GetPlateAnnotationInfosAsync();
                System.Diagnostics.Debug.WriteLine($"从数据库查询到 {allPlateAnnotationInfos.Count} 条PlateAnnotationInfo记录");
                
                // 步骤2：根据工作空间进行过滤
                List<PlateAnnotationInfo> filteredInfos;
                
                if (WorkSpaceId > 0)
                {
                    // 有工作空间ID，加载工作空间并进行过滤
                    var workSpace = await _workSpaceService.GetWorkSpaceByIdAsync(WorkSpaceId);
                    if (workSpace != null)
                    {
                        _workSpaceService.SetCurrentWorkSpace(workSpace);
                        
                        // 更新工作空间节点
                        if (workSpace.WorkSpaceNodes != null)
                        {
                            LoadWorkSpaceNodes(workSpace.WorkSpaceNodes);
                        }
                        
                        // 基于工作空间节点进行过滤（使用OR关系，更灵活）
                        filteredInfos = FilterPlateAnnotationInfosByWorkSpaceFlexible(allPlateAnnotationInfos, workSpace.WorkSpaceNodes);
                        System.Diagnostics.Debug.WriteLine($"工作空间过滤后剩余 {filteredInfos.Count} 条记录");
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"未找到工作空间ID: {WorkSpaceId}，显示所有数据");
                        filteredInfos = allPlateAnnotationInfos;
                    }
                }
                else
                {
                    // 没有工作空间ID，显示所有数据
                    System.Diagnostics.Debug.WriteLine("没有工作空间ID，显示所有数据");
                    filteredInfos = allPlateAnnotationInfos;
                }
                
                // 步骤3：转换为ViewModel并更新UI
                var viewModels = filteredInfos.Select(info => new PlateAnnotationInfoViewModel(info)).ToList();
                
                // 订阅选择状态改变事件
                foreach (var item in viewModels)
                {
                    item.SelectionChanged += OnItemSelectionChanged;
                }
                
                // 同时设置PlateAnnotationInfos和FilteredPlateAnnotationInfos
                // PlateAnnotationInfos用于查询条件控件的绑定
                // FilteredPlateAnnotationInfos用于实际的数据显示和合并
                PlateAnnotationInfos = new ObservableCollection<PlateAnnotationInfoViewModel>(viewModels);
                FilteredPlateAnnotationInfos = new ObservableCollection<PlateAnnotationInfoViewModel>(viewModels);
                
                System.Diagnostics.Debug.WriteLine($"ProcessSequenceView数据加载完成，显示 {viewModels.Count} 条记录");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载ProcessSequenceView数据失败: {ex.Message}");
                MessageBox.Show($"加载数据失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 基于工作空间节点进行灵活过滤（使用OR关系，更宽松）
        /// </summary>
        private List<PlateAnnotationInfo> FilterPlateAnnotationInfosByWorkSpaceFlexible(List<PlateAnnotationInfo> allInfos, List<WorkSpaceNode> workSpaceNodes)
        {
            if (workSpaceNodes == null || workSpaceNodes.Count == 0)
            {
                return allInfos;
            }
            
            // 收集工作空间中的所有船号、LOT号、加工序列
            var shipNumbers = new HashSet<string>();
            var lotNumbers = new HashSet<string>();
            var sequences = new HashSet<string>();
            
            CollectWorkSpaceNodeValues(workSpaceNodes, shipNumbers, lotNumbers, sequences);
            
            System.Diagnostics.Debug.WriteLine($"工作空间节点 - 船号: {string.Join(",", shipNumbers)}, LOT号: {string.Join(",", lotNumbers)}, 加工序列: {string.Join(",", sequences)}");
            
            // 灵活过滤：匹配船号 OR LOT号 OR 加工序列（任一匹配即可）
            var filteredInfos = allInfos.Where(info =>
                shipNumbers.Contains(info.StreamShipNo) &&
                lotNumbers.Contains(info.LotNo) &&
                sequences.Contains(info.Sequence)
            ).ToList();
            
            return filteredInfos;
        }

        /// <summary>
        /// 基于工作空间节点进行精确过滤（船号 AND LOT号 AND 加工序列）
        /// </summary>
        private List<PlateAnnotationInfo> FilterPlateAnnotationInfosByWorkSpace(List<PlateAnnotationInfo> allInfos, List<WorkSpaceNode> workSpaceNodes)
        {
            if (workSpaceNodes == null || workSpaceNodes.Count == 0)
            {
                return allInfos;
            }
            
            // 收集工作空间中的所有船号、LOT号、加工序列
            var shipNumbers = new HashSet<string>();
            var lotNumbers = new HashSet<string>();
            var sequences = new HashSet<string>();
            
            CollectWorkSpaceNodeValues(workSpaceNodes, shipNumbers, lotNumbers, sequences);
            
            System.Diagnostics.Debug.WriteLine($"工作空间节点 - 船号: {string.Join(",", shipNumbers)}, LOT号: {string.Join(",", lotNumbers)}, 加工序列: {string.Join(",", sequences)}");
            
            // 精确过滤：必须同时匹配船号 AND LOT号 AND 加工序列
            var filteredInfos = allInfos.Where(info =>
                shipNumbers.Contains(info.StreamShipNo) &&
                lotNumbers.Contains(info.LotNo) &&
                sequences.Contains(info.Sequence)
            ).ToList();
            
            return filteredInfos;
        }

        /// <summary>
        /// 递归收集工作空间节点中的船号、LOT号、加工序列
        /// </summary>
        private void CollectWorkSpaceNodeValues(List<WorkSpaceNode> nodes, HashSet<string> shipNumbers, HashSet<string> lotNumbers, HashSet<string> sequences)
        {
            foreach (var node in nodes)
            {
                switch (node.NodeType)
                {
                    case "Ship":
                        shipNumbers.Add(node.NodeValue);
                        break;
                    case "Lot":
                        lotNumbers.Add(node.NodeValue);
                        break;
                    case "Sequence":
                        sequences.Add(node.NodeValue);
                        break;
                }
                
                // 递归处理子节点
                if (node.Children != null && node.Children.Count > 0)
                {
                    CollectWorkSpaceNodeValues(node.Children, shipNumbers, lotNumbers, sequences);
                }
            }
        }

        // 加载与当前工作空间相关的全部数据（保留用于向后兼容）
        private async Task LoadWorkSpaceRelatedDataAsync()
        {
            try
            {
                var currentWorkSpace = _workSpaceService.GetCurrentWorkSpace();
                if (currentWorkSpace?.WorkSpaceNodes == null || currentWorkSpace.WorkSpaceNodes.Count == 0)
                {
                    // 工作空间为空，清空标注信息
                    PlateAnnotationInfos?.Clear();
                    FilteredPlateAnnotationInfos?.Clear();
                    return;
                }

                // 获取所有标注信息
                await SyncAndMergeAllSourcesAsync();

                // 根据工作空间节点过滤相关数据
                var workSpaceNodeNames = CollectWorkSpaceNodeNames(currentWorkSpace.WorkSpaceNodes);
                var filteredViewModels = PlateAnnotationInfos?.Where(info =>
                    workSpaceNodeNames.Contains(info.StreamShipNo) ||
                    workSpaceNodeNames.Contains(info.LotNo) ||
                    workSpaceNodeNames.Contains(info.Sequence)).ToList() ?? new List<PlateAnnotationInfoViewModel>();

                // 更新过滤后的数据
                FilteredPlateAnnotationInfos = new ObservableCollection<PlateAnnotationInfoViewModel>(filteredViewModels);
                System.Diagnostics.Debug.WriteLine($"工作空间相关数据数量: {filteredViewModels.Count}");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载工作空间相关数据失败: {ex.Message}");
            }
        }


        // 收集工作空间节点名称
        private HashSet<string> CollectWorkSpaceNodeNames(List<WorkSpaceNode> nodes)
        {
            var nodeNames = new HashSet<string>();
            foreach (var node in nodes)
            {
                if (!string.IsNullOrEmpty(node.Name))
                {
                    nodeNames.Add(node.Name);
                }

                if (node.Children != null && node.Children.Count > 0)
                {
                    var childNames = CollectWorkSpaceNodeNames(node.Children);
                    foreach (var childName in childNames)
                    {
                        nodeNames.Add(childName);
                    }
                }
            }
            return nodeNames;
        }

        /// <summary>
        /// 判断数据是否存在于工作空间节点中
        /// 三级树节点分别对应keyShip，keyLot，keySeq，该三级节点名称都相等才行
        /// </summary>
        /// <param name="keyShip">船号</param>
        /// <param name="keyLot">LOT号</param>
        /// <param name="keySeq">加工序列</param>
        /// <returns>如果数据存在于工作空间中返回true，否则返回false</returns>
        private bool IsDataInWorkSpace(string keyShip, string keyLot, string keySeq)
        {
            try
            {
                // 获取当前工作空间
                if (WorkSpaceNodes == null || WorkSpaceNodes.Count == 0)
                {
                    // 如果没有工作空间或工作空间为空，则不过滤，返回true
                    return true;
                }

                // 递归查找三级节点匹配
                return FindMatchingWorkSpaceNode(WorkSpaceNodes, keyShip, keyLot, keySeq);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"判断数据是否在工作空间中失败: {ex.Message}");
                // 发生异常时，为了安全起见，返回true（不过滤）
                return true;
            }
        }

        /// <summary>
        /// 递归查找匹配的工作空间节点
        /// </summary>
        /// <param name="nodes">工作空间节点列表</param>
        /// <param name="keyShip">船号</param>
        /// <param name="keyLot">LOT号</param>
        /// <param name="keySeq">加工序列</param>
        /// <returns>如果找到匹配的三级节点返回true，否则返回false</returns>
        private bool FindMatchingWorkSpaceNode(ObservableCollection<BaseInfoTreeNode> nodes, string keyShip, string keyLot, string keySeq)
        {

            if (nodes == null || nodes.Count == 0)
                return false;

            foreach (var node in nodes)
            {
                // 第一级：船号匹配
                if (string.Equals(node.Name, keyShip, StringComparison.OrdinalIgnoreCase))
                {
                    // 第二级：LOT号匹配
                    if (node.Children != null && node.Children.Count > 0)
                    {
                        foreach (var lotNode in node.Children)
                        {
                            if (string.Equals(lotNode.Name, keyLot, StringComparison.OrdinalIgnoreCase))
                            {
                                // 第三级：加工序列匹配
                                if (lotNode.Children != null && lotNode.Children.Count > 0)
                                {
                                    foreach (var seqNode in lotNode.Children)
                                    {
                                        if (string.Equals(seqNode.Name, keySeq, StringComparison.OrdinalIgnoreCase))
                                        {
                                            // 找到完整的三级匹配
                                            System.Diagnostics.Debug.WriteLine($"找到匹配的工作空间节点: 船号={keyShip}, LOT={keyLot}, 序列={keySeq}");
                                            return true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                // 递归查找子节点
                if (node.Children != null && node.Children.Count > 0)
                {
                    if (FindMatchingWorkSpaceNode(node.Children, keyShip, keyLot, keySeq))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        private void EditWorkSpace()
        {
            try
            {
                var vm = new AddBaseInfoViewModel(_workSpaceService, _eventAggregator);
                var dialog = new AddBaseInfoView();
                dialog.DataContext = vm;
                dialog.Owner = System.Windows.Application.Current.MainWindow;
                dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                var result = dialog.ShowDialog();
                if (result == true)
                {
                    // 工作空间编辑成功，刷新工作空间
                    _ = RefreshWorkSpaceAsync();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"编辑工作空间失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        // 工作空间节点选择事件处理
        public async void OnWorkSpaceNodeSelected(BaseInfoTreeNode selectedNode)
        {
            if (selectedNode == null) return;

            try
            {
                System.Diagnostics.Debug.WriteLine($"选中树节点: {selectedNode.Name}");

                // 根据选中的节点类型进行不同的过滤
                var filteredInfos = await FilterPlateAnnotationInfosByNodeAsync(selectedNode);

                // 只更新过滤后的显示列表，不修改原始数据
                var viewModels = new ObservableCollection<PlateAnnotationInfoViewModel>(
                    filteredInfos.Select(info => new PlateAnnotationInfoViewModel(info))
                );

                // 订阅选择状态改变事件
                foreach (var item in viewModels)
                {
                    item.SelectionChanged += OnItemSelectionChanged;
                }

                FilteredPlateAnnotationInfos = viewModels;

                System.Diagnostics.Debug.WriteLine($"过滤后的标注信息数量: {filteredInfos.Count}");

                // 调试：输出所有可用数据的船号信息
                var allInfos = await GetAllPlateAnnotationInfosAsync();
                var availableShipNos = allInfos.Select(info => info.StreamShipNo).Distinct().ToList();
                System.Diagnostics.Debug.WriteLine($"所有可用数据的船号: {string.Join(", ", availableShipNos)}");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载节点数据失败: {ex.Message}");
                MessageBox.Show($"加载节点数据失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        // 根据树节点过滤标注信息
        private async Task<List<PlateAnnotationInfo>> FilterPlateAnnotationInfosByNodeAsync(BaseInfoTreeNode selectedNode)
        {
            var allInfos = await GetAllPlateAnnotationInfosAsync();
            var filteredInfos = new List<PlateAnnotationInfo>();

            System.Diagnostics.Debug.WriteLine($"开始过滤，总数据量: {allInfos.Count}");
            System.Diagnostics.Debug.WriteLine($"选中节点: {selectedNode.Name}, 父节点: {(selectedNode.Parent?.Name ?? "无")}, 祖父节点: {(selectedNode.Parent?.Parent?.Name ?? "无")}");

            // 根据节点类型进行过滤
            if (selectedNode.Parent == null)
            {
                // 第1级节点（船号）
                filteredInfos = allInfos.Where(info => info.StreamShipNo == selectedNode.Name).ToList();
                System.Diagnostics.Debug.WriteLine($"第1级节点过滤 - 船号: {selectedNode.Name}, 匹配条件: StreamShipNo == {selectedNode.Name}");
            }
            else if (selectedNode.Parent.Parent == null)
            {
                // 第2级节点（LOT号）
                filteredInfos = allInfos.Where(info =>
                    info.StreamShipNo == selectedNode.Parent.Name &&
                    info.LotNo == selectedNode.Name).ToList();
                System.Diagnostics.Debug.WriteLine($"第2级节点过滤 - 船号: {selectedNode.Parent.Name}, LOT号: {selectedNode.Name}");
            }
            else
            {
                // 第3级节点（加工序列）
                filteredInfos = allInfos.Where(info =>
                    info.StreamShipNo == selectedNode.Parent.Parent.Name &&
                    info.LotNo == selectedNode.Parent.Name &&
                    info.Sequence == selectedNode.Name).ToList();
                System.Diagnostics.Debug.WriteLine($"第3级节点过滤 - 船号: {selectedNode.Parent.Parent.Name}, LOT号: {selectedNode.Parent.Name}, 序列: {selectedNode.Name}");
            }

            // 调试：输出匹配的数据详情
            if (filteredInfos.Count > 0)
            {
                var sampleInfo = filteredInfos.First();
                System.Diagnostics.Debug.WriteLine($"匹配到的第一条数据 - 船号: {sampleInfo.StreamShipNo}, LOT号: {sampleInfo.LotNo}, 序列: {sampleInfo.Sequence}");
            }

            return filteredInfos;
        }

        // 获取所有标注信息
        private async Task<List<PlateAnnotationInfo>> GetAllPlateAnnotationInfosAsync()
        {
            // 如果已经有数据，直接返回（转换为PlateAnnotationInfo）
            if (PlateAnnotationInfos != null && PlateAnnotationInfos.Count > 0)
            {
                System.Diagnostics.Debug.WriteLine($"使用缓存数据，数量: {PlateAnnotationInfos.Count}");
                return PlateAnnotationInfos.Select(vm => vm.OriginalData).ToList();
            }

            // 否则重新加载所有数据
            System.Diagnostics.Debug.WriteLine("缓存数据为空，重新加载所有数据");
            await SyncAndMergeAllSourcesAsync();
            var result = PlateAnnotationInfos?.Select(vm => vm.OriginalData).ToList() ?? new List<PlateAnnotationInfo>();
            System.Diagnostics.Debug.WriteLine($"重新加载完成，数据数量: {result.Count}");
            return result;
        }


        // 加载KMACS数据并转换为PlateAnnotationInfoViewModel
        private async Task LoadKmacsPlateAnnotationInfosAsync()
        {
            var list = await _kmacsService.GetProcessInfosAsync();
            var plateList = list.Select(PlateAnnotationInfoFactory.FromKmacsDto).ToList();
            var viewModels = plateList.Select(info => new PlateAnnotationInfoViewModel(info)).ToList();
            PlateAnnotationInfos = new ObservableCollection<PlateAnnotationInfoViewModel>(viewModels);
        }

        // 加载AM数据并转换为PlateAnnotationInfoViewModel
        private async Task LoadAmPlateAnnotationInfosAsync()
        {
            var list = await _amService.GetDrawingInfosAsync();
            var plateList = list.Select(PlateAnnotationInfoFactory.FromAmDto).ToList();
            var viewModels = plateList.Select(info => new PlateAnnotationInfoViewModel(info)).ToList();
            PlateAnnotationInfos = new ObservableCollection<PlateAnnotationInfoViewModel>(viewModels);
        }

        // 加载CadWin数据并转换为PlateAnnotationInfoViewModel
        private async Task LoadCadWinPlateAnnotationInfosAsync()
        {
            var list = await _cadWinService.GetDrawingInfosAsync();
            var plateList = list.Select(PlateAnnotationInfoFactory.FromCadWinDto).ToList();
            var viewModels = plateList.Select(info => new PlateAnnotationInfoViewModel(info)).ToList();
            PlateAnnotationInfos = new ObservableCollection<PlateAnnotationInfoViewModel>(viewModels);
        }

        /// <summary>
        /// 从数据库获取标注信息数据
        /// </summary>
        private async Task LoadDataFromDatabaseAsync()
        {
            try
            {
                // 从数据库获取所有标注信息
                var plateAnnotationInfos = await _dataSyncService.GetPlateAnnotationInfosAsync();
                
                // 转换为ViewModel
                var viewModels = plateAnnotationInfos.Select(info => new PlateAnnotationInfoViewModel(info)).ToList();
                
                // 更新集合
                FilteredPlateAnnotationInfos = new ObservableCollection<PlateAnnotationInfoViewModel>(viewModels);
                
                // 应用当前筛选条件
                await ApplyFilterAsync();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"从数据库加载数据失败: {ex.Message}");
                // 如果数据库加载失败，可以回退到原来的逻辑或显示错误信息
            }
        }

        /// <summary>
        /// 同步并合并KMACS、AM、CadWin三方数据，生成最新PlateAnnotationInfo集合
        /// 注意：此方法已被LoadDataFromDatabaseAsync替代，保留用于向后兼容
        /// </summary>
        private async Task SyncAndMergeAllSourcesAsync()
        {
            // 直接调用新的数据库加载方法
            await LoadDataFromDatabaseAsync();
        }

        private async Task ApplyFilterAsync()
        {
            IsQuerying = true;
            
            try
            {
                // 基于当前PlateAnnotationInfos进行过滤，而不是重新从数据库查询
                // 这样可以确保只对当前工作空间的数据进行筛选
                var currentData = PlateAnnotationInfos?.ToList() ?? new List<PlateAnnotationInfoViewModel>();
                
                System.Diagnostics.Debug.WriteLine($"开始应用筛选条件，当前数据量: {currentData.Count}");
                System.Diagnostics.Debug.WriteLine($"筛选条件 - 船号: {SelectedStreamShipNo}, LOT号: {SelectedLotNo}, 加工序列: {SelectedSequence}");
                
                var filteredData = currentData.AsEnumerable();

                // 应用船号筛选
                if (!string.IsNullOrEmpty(SelectedStreamShipNo) && SelectedStreamShipNo != "全部")
                {
                    filteredData = filteredData.Where(x => x.StreamShipNo == SelectedStreamShipNo);
                }

                // 应用LOT号筛选
                if (!string.IsNullOrEmpty(SelectedLotNo) && SelectedLotNo != "全部")
                {
                    filteredData = filteredData.Where(x => x.LotNo == SelectedLotNo);
                }

                // 应用加工序列筛选
                if (!string.IsNullOrEmpty(SelectedSequence) && SelectedSequence != "全部")
                {
                    filteredData = filteredData.Where(x => x.Sequence == SelectedSequence);
                }

                // 应用使用预定日筛选
                if (SelectedPlanUsedDateStart.HasValue)
                {
                    filteredData = filteredData.Where(x => x.PlanUsedDate >= SelectedPlanUsedDateStart.Value);
                }

                if (SelectedPlanUsedDateEnd.HasValue)
                {
                    filteredData = filteredData.Where(x => x.PlanUsedDate <= SelectedPlanUsedDateEnd.Value);
                }

                // 应用标注状态筛选
                if (!string.IsNullOrEmpty(SelectedAnnotationStatus) && SelectedAnnotationStatus != "全部")
                {
                    bool isAnnotated = SelectedAnnotationStatus == "已标注";
                    filteredData = filteredData.Where(x => x.IsAnnotationGenerated == isAnnotated);
                }

                var filteredList = filteredData.ToList();
                System.Diagnostics.Debug.WriteLine($"筛选后数据量: {filteredList.Count}");

                var viewModels = new ObservableCollection<PlateAnnotationInfoViewModel>(filteredList);

                // 订阅选择状态改变事件
                foreach (var item in viewModels)
                {
                    item.SelectionChanged += OnItemSelectionChanged;
                }

                FilteredPlateAnnotationInfos = viewModels;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"应用筛选条件失败: {ex.Message}");
            }
            finally
            {
                IsQuerying = false;
            }
        }

        private async void ResetFilter()
        {
            SelectedStreamShipNo = "全部";
            SelectedLotNo = "全部";
            SelectedSequence = "全部";
            SelectedPlanUsedDateStart = null;
            SelectedPlanUsedDateEnd = null;
            SelectedAnnotationStatus = "全部";

            // 如果没有选中的工作空间节点，显示全部数据
            System.Diagnostics.Debug.WriteLine("重置过滤器，没有选中的工作空间节点，显示全部数据");
            var viewModels = new ObservableCollection<PlateAnnotationInfoViewModel>(PlateAnnotationInfos);

            // 订阅选择状态改变事件
            foreach (var item in viewModels)
            {
                item.SelectionChanged += OnItemSelectionChanged;
            }

            FilteredPlateAnnotationInfos = viewModels;


            RaisePropertyChanged(nameof(SelectedStreamShipNo));
            RaisePropertyChanged(nameof(SelectedLotNo));
            RaisePropertyChanged(nameof(SelectedSequence));
            RaisePropertyChanged(nameof(SelectedPlanUsedDateStart));
            RaisePropertyChanged(nameof(SelectedPlanUsedDateEnd));
            RaisePropertyChanged(nameof(SelectedAnnotationStatus));
        }

        /// <summary>
        /// 执行全选/反选命令
        /// </summary>
        private void ExecuteSelectAll()
        {
            if (MergedPlateAnnotationInfos == null || MergedPlateAnnotationInfos.Count == 0)
                return;

            // 设置批量操作标志，防止触发单行选择状态改变事件
            _isBatchSelecting = true;

            try
            {
                foreach (var item in MergedPlateAnnotationInfos)
                {
                    item.IsSelected = IsAllSelected;
                }
            }
            finally
            {
                // 恢复标志
                _isBatchSelecting = false;
            }
        }

        /// <summary>
        /// 检查是否可以执行全选命令
        /// </summary>
        private bool CanExecuteSelectAll()
        {
            return MergedPlateAnnotationInfos != null && MergedPlateAnnotationInfos.Count > 0;
        }

        /// <summary>
        /// 创建合并数据
        /// </summary>
        private void CreateMergedData()
        {
            var mergedData = new ObservableCollection<MergedPlateAnnotationInfoViewModel>();
            int mergedId = 1; // 新的递增ID，从1开始

            if (FilteredPlateAnnotationInfos == null || FilteredPlateAnnotationInfos.Count == 0)
            {
                MergedPlateAnnotationInfos = mergedData;
                return;
            }

            // 调试输出：显示所有记录的处理方式和合并信息
            System.Diagnostics.Debug.WriteLine("=== 开始分析合并数据 ===");
            foreach (var item in FilteredPlateAnnotationInfos)
            {
                System.Diagnostics.Debug.WriteLine($"记录ID: {item.Id}, 钢板一贯编号: {item.SheetConsistentNo}, 处理方式: {item.LayoutMean}, 合并信息: '{item.MergedInfo}', LayoutInfo: {(string.IsNullOrEmpty(item.LayoutInfo) ? "空" : "有数据")}");
            }

            // 按LayoutInfo分组，有合并信息的记录会被分组
            var groupedData = FilteredPlateAnnotationInfos
                .GroupBy(x => GetMergeKey(x)) // 根据合并信息生成分组键
                .ToList();

            System.Diagnostics.Debug.WriteLine($"开始创建合并数据，原始记录数: {FilteredPlateAnnotationInfos.Count}, 分组数: {groupedData.Count}");

            // 调试输出：显示每个分组的键和记录
            foreach (var group in groupedData)
            {
                var groupList = group.ToList();
                var groupKey = group.Key;
                System.Diagnostics.Debug.WriteLine($"分组键: '{groupKey}', 记录数: {groupList.Count}");
                foreach (var item in groupList)
                {
                    System.Diagnostics.Debug.WriteLine($"  - 记录ID: {item.Id}, 钢板一贯编号: {item.SheetConsistentNo}, 处理方式: {item.LayoutMean}");
                }
            }

            foreach (var group in groupedData)
            {
                var groupList = group.ToList();
                
                if (groupList.Count > 1) // 需要合并的记录
                {
                    var originalIds = groupList.Select(x => x.Id).ToList();
                    var sheetConsistentNos = groupList.Select(x => x.SheetConsistentNo).ToList();
                    System.Diagnostics.Debug.WriteLine($"合并记录 - 显示ID: {mergedId}, 原始ID: {string.Join(",", originalIds)}, 钢板一贯编号: {string.Join(",", sheetConsistentNos)}");
                    
                    var mergedItem = new MergedPlateAnnotationInfoViewModel(groupList.First(), groupList)
                    {
                        MergedId = mergedId++ // 合并记录只占用一个ID位置
                    };
                    
                    // 同步选择状态
                    mergedItem.IsSelected = groupList.Any(x => x.IsSelected);
                    // 订阅选择状态变化事件
                    mergedItem.SelectionChanged += OnMergedItemSelectionChanged;
                    mergedData.Add(mergedItem);
                }
                else // 单条记录
                {
                    System.Diagnostics.Debug.WriteLine($"单条记录 - 显示ID: {mergedId}, 原始ID: {groupList.First().Id}, 钢板一贯编号: {groupList.First().SheetConsistentNo}");
                    
                    var singleItem = new MergedPlateAnnotationInfoViewModel(groupList.First(), groupList)
                    {
                        MergedId = mergedId++ // 单条记录占用一个ID位置
                    };
                    
                    // 同步选择状态
                    singleItem.IsSelected = groupList.First().IsSelected;
                    // 订阅选择状态变化事件
                    singleItem.SelectionChanged += OnMergedItemSelectionChanged;
                    mergedData.Add(singleItem);
                }
            }

            System.Diagnostics.Debug.WriteLine($"合并完成，显示记录数: {mergedData.Count}");
            
            // 调试输出合并数据
            foreach (var item in mergedData)
            {
                if (item.IsMerged)
                {
                    System.Diagnostics.Debug.WriteLine($"合并项 - ID: {item.MergedId}, 船号: '{item.StreamShipNo}', CNO: '{item.CNO}', 钢板一贯编号: '{item.SheetConsistentNo}', 合并信息: '{item.MergedInfo}'");
                }
            }
            
            MergedPlateAnnotationInfos = mergedData;
        }

        /// <summary>
        /// 生成合并分组键的方法
        /// </summary>
        private string GetMergeKey(PlateAnnotationInfoViewModel item)
        {
            // 检查是否有合并信息
            if (!string.IsNullOrEmpty(item.LayoutInfo) && item.LayoutInfo.Contains("Merged"))
            {
                try
                {
                    // 尝试解析JSON格式的合并信息
                    var layoutInfo = JsonConvert.DeserializeObject<LayoutInfo>(item.LayoutInfo);
                    if (layoutInfo?.Merged?.PartLayouts != null && layoutInfo.Merged.PartLayouts.Any())
                    {
                        // 使用合并信息中的PartLayouts作为分组键
                        var partLayouts = layoutInfo.Merged.PartLayouts
                            .Select(p => p.SheetConsistentNo)
                            .OrderBy(x => x)
                            .ToList();
                        return $"merged_{string.Join("_", partLayouts)}";
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"解析合并信息失败: {ex.Message}");
                }
            }
            
            // 检查MergedInfo字段（备用方案）
            if (!string.IsNullOrEmpty(item.MergedInfo))
            {
                var mergedParts = item.MergedInfo.Split(',')
                    .Select(x => x.Trim())
                    .Where(x => !string.IsNullOrEmpty(x))
                    .OrderBy(x => x)
                    .ToList();
                if (mergedParts.Count > 1)
                {
                    return $"merged_{string.Join("_", mergedParts)}";
                }
            }
            
            // 否则使用唯一标识作为分组键（不合并）
            return $"single_{item.Id}";
        }

        /// <summary>
        /// 更新全选状态（当单个项目选择状态改变时调用）
        /// </summary>
        private void UpdateSelectAllState()
        {
            if (MergedPlateAnnotationInfos == null || MergedPlateAnnotationInfos.Count == 0)
            {
                IsAllSelected = false;
                return;
            }

            var selectedCount = MergedPlateAnnotationInfos.Count(x => x.IsSelected);
            IsAllSelected = selectedCount == MergedPlateAnnotationInfos.Count;
        }

        /// <summary>
        /// 当单个项目选择状态改变时的处理
        /// </summary>
        private void OnItemSelectionChanged()
        {
            // 如果是批量操作，跳过更新
            if (_isBatchSelecting)
                return;

            // 只更新全选状态，不强制同步合并项的选择状态
            // 让合并项的选择状态由用户操作自然控制
            UpdateSelectAllState();
            
            // 重新评估标注命令的可执行状态
            AnnotationCommand?.RaiseCanExecuteChanged();

            // 重新评估导出图纸命令的可执行状态
            ExportDocumentsCommand?.RaiseCanExecuteChanged();

            //重新评估合并布局命令的可执行状态
            MergeLayoutCommand?.RaiseCanExecuteChanged();
        }

        /// <summary>
        /// 当合并项的选择状态改变时调用
        /// </summary>
        private void OnMergedItemSelectionChanged()
        {
            // 如果是批量操作，跳过更新
            if (_isBatchSelecting)
                return;

            // 更新全选状态
            UpdateSelectAllState();
            
            // 重新评估标注命令的可执行状态
            AnnotationCommand?.RaiseCanExecuteChanged();

            // 重新评估导出图纸命令的可执行状态
            ExportDocumentsCommand?.RaiseCanExecuteChanged();

            //重新评估合并布局命令的可执行状态
            MergeLayoutCommand?.RaiseCanExecuteChanged();
        }

        #region binding methods
        private void MoundCommand()
        {
            BtnSyncCommand = new DelegateCommand(BtnSync, () => true);
            DxfAnnotateCommand = new DelegateCommand(DxfAnnotate, CanDxfAnnotate);
            SheetLayoutCommand = new DelegateCommand(DoSheetLayout);
        }


        public DelegateCommand BtnSyncCommand { get; set; }
        public DelegateCommand DxfAnnotateCommand { get; set; }

        public DelegateCommand SheetLayoutCommand { get; set; }
        public DelegateCommand MergeLayoutCommand { get; set; }
        public DelegateCommand AutoMirrorLayoutCommand { get; set; }

        private void BtnSync()
        {
            var newWindow = new PSSync();
            newWindow.ShowDialog();
        }

        private void DxfAnnotate()
        {
            _eventAggregator.GetEvent<ShowAnnotationModeEvent>().Publish(true);
            _regionManager.RequestNavigate(ConstStrings.UI_Region_Main_Content, "DxfAnnotationView");
        }

        private async void DoSheetLayout()
        {
            _eventAggregator.GetEvent<ShowAnnotationModeEvent>().Publish(true);
            _regionManager.RequestNavigate(ConstStrings.UI_Region_Main_Content, "SheetLayoutView");

            await Task.Delay(100);

            _eventAggregator.GetEvent<StartDispalySheetLayoutEvents>().Publish("testSheetLayoutId");
        }

        /// <summary>
        /// 执行手动合并布局
        /// </summary>
        private async Task ExecuteMergeLayoutAsync()
        {
            try
            {
                var selectedMergedItems = MergedPlateAnnotationInfos?.Where(x => x.IsSelected).ToList() ?? new List<MergedPlateAnnotationInfoViewModel>();
                if (!selectedMergedItems.Any())
                {
                    MessageBox.Show("请选择要处理的记录", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                var selectedData = GetSelectedOriginalData();
                if (selectedData.Count < 2)
                {
                    MessageBox.Show("请至少选择2个图纸进行合并布局", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 检查是否选中了已合并的数据
                bool isAdjustingMergedLayout = selectedMergedItems.Count == 1 && selectedMergedItems.First().GetAllOriginalData().Count > 1;
                
                if (isAdjustingMergedLayout)
                {
                    // 调整已合并的布局
                    var mergedItem = selectedMergedItems.First();
                    var layoutInfo = GetLayoutInfoFromMergedItem(mergedItem);
                    
                    System.Diagnostics.Debug.WriteLine($"调整已合并布局，包含 {selectedData.Count} 个原始数据项");
                    
                    if (layoutInfo != null)
                    {
                        System.Diagnostics.Debug.WriteLine($"找到布局信息，包含 {layoutInfo.Merged?.PartLayouts?.Count ?? 0} 个零件布局");
                        
                        // 直接导航到布局视图并传递已合并的布局信息
                        _eventAggregator.GetEvent<ShowAnnotationModeEvent>().Publish(true);
                        _regionManager.RequestNavigate(ConstStrings.UI_Region_Main_Content, "SheetLayoutView");

                        await Task.Delay(100);

                        // 发布已合并的布局信息到布局视图进行调整
                        this._eventAggregator.GetEvent<SheetLayoutAdjustEvent>().Publish(selectedData.ToList());
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("未找到布局信息，将作为新布局处理");
                        
                        // 即使没有布局信息，也允许用户进行调整
                        _eventAggregator.GetEvent<ShowAnnotationModeEvent>().Publish(true);
                        _regionManager.RequestNavigate(ConstStrings.UI_Region_Main_Content, "SheetLayoutView");

                        await Task.Delay(100);

                        this._eventAggregator.GetEvent<SheetLayoutAdjustEvent>().Publish(selectedData.ToList());
                    }
                }
                else
                {
                    // 创建新的合并布局
                    // 计算最大钢板尺寸
                    var maxLength = selectedData.Max(s => s.SheetSpecLength);
                    var maxWidth = selectedData.Max(s => s.SheetSpecWidth);

                    // 验证布局是否可行
                    var validation = await _layoutService.ValidateMergeLayoutAsync(selectedData, maxLength, maxWidth);
                    if (!validation.IsValid)
                    {
                        MessageBox.Show(validation.ErrorMessage, "布局验证失败", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }

                    _eventAggregator.GetEvent<ShowAnnotationModeEvent>().Publish(true);
                    _regionManager.RequestNavigate(ConstStrings.UI_Region_Main_Content, "SheetLayoutView");

                    await Task.Delay(100);

                    this._eventAggregator.GetEvent<SheetLayoutAdjustEvent>().Publish(selectedData.ToList());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"执行合并布局时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }


        private bool CanMergeLayout()
        {
            // 使用与标注按钮和输出图纸按钮相同的数据源
            var selectedMergedItems = MergedPlateAnnotationInfos?.Where(x => x.IsSelected).ToList() ?? new List<MergedPlateAnnotationInfoViewModel>();
            if (selectedMergedItems.Count == 0)
                return false;
            
            // 如果只选中了一个合并项，检查它是否已经包含多个原始数据（已合并的数据）
            if (selectedMergedItems.Count == 1)
            {
                var selectedItem = selectedMergedItems.First();
                // 如果选中的项已经包含多个原始数据，说明是已合并的数据，可以进行布局调整
                return selectedItem.GetAllOriginalData().Count > 1;
            }
            
            // 如果选中了多个合并项，检查是否包含足够的原始数据（至少2个原始数据项）
            var totalOriginalDataCount = selectedMergedItems.Sum(x => x.GetAllOriginalData().Count);
            return totalOriginalDataCount > 1;
        }

        /// <summary>
        /// 执行镜像自动布局
        /// </summary>
        private async Task ExecuteAutoMirrorLayoutAsync()
        {
            try
            {
                var unprocessedOriginalData = FilteredPlateAnnotationInfos
                    .Where(p => p.LayoutMean == LayoutMean.Unprocessed)
                    .Select(p => p.OriginalData)
                    .ToList();

                if (!unprocessedOriginalData.Any())
                {
                    MessageBox.Show("没有找到未处理的图纸", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 执行镜像自动布局
                var success = await _layoutService.ExecuteMirrorAutoLayoutAsync(unprocessedOriginalData);
                if (success)
                {
                    MessageBox.Show("镜像自动布局成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    await ApplyFilterAsync(); // 刷新数据
                }
                else
                {
                    MessageBox.Show("镜像自动布局失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"执行镜像自动布局时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 执行输出图纸
        /// </summary>
        private void ExecuteExportDocuments()
        {
            try
            {
                // 获取选中的已标注完成的图纸
                var selectedMergedItems = MergedPlateAnnotationInfos
                    .Where(x => x.IsSelected && x.HasAnnotationGenerated)
                    .ToList();

                if (!selectedMergedItems.Any())
                {
                    MessageBox.Show("请选择已标注完成的图纸进行输出。", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // 将合并项转换为原始ViewModel列表
                var selectedCompletedItems = new List<PlateAnnotationInfoViewModel>();
                foreach (var mergedItem in selectedMergedItems)
                {
                    selectedCompletedItems.AddRange(mergedItem.GetAllOriginalData().Select(data => new PlateAnnotationInfoViewModel(data)));
                }

                // 创建并显示输出图纸对话框
                var plateAnnotationRepository = Prism.Ioc.ContainerLocator.Container.Resolve(typeof(IPlateAnnotationInfoRepository)) as IPlateAnnotationInfoRepository;
                var vm = new ExportDocumentsViewModel(_globalConfigService, selectedCompletedItems, plateAnnotationRepository);
                var dialog = new ExportDocumentsView();
                dialog.DataContext = vm;
                dialog.Owner = App.Current.MainWindow;
                dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                var result = dialog.ShowDialog();
                
                // 如果导出成功，刷新合并数据以更新UI显示
                if (result == true)
                {
                    CreateMergedData();
                    System.Diagnostics.Debug.WriteLine("导出完成后已刷新合并数据");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"输出图纸时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 检查是否可以执行输出图纸命令
        /// </summary>
        private bool CanExecuteExportDocuments()
        {
            // 检查是选中的已标注完成的图纸
            var selectedMergedItems = MergedPlateAnnotationInfos?.Where(x => x.IsSelected).ToList() ?? new List<MergedPlateAnnotationInfoViewModel>();
            return selectedMergedItems.Any(x => x.HasAnnotationGenerated);
        }

        /// <summary>
        /// 执行标注命令
        /// </summary>
        private void ExecuteAnnotation()
        {
            try
            {
                // 获取当前选中的项
                var selectedItem = GetCurrentSelectedItem();
                if (selectedItem == null)
                {
                    MessageBox.Show("请先选择要标注的记录。", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                _eventAggregator.GetEvent<EditPlateAnnotationEvent>().Publish(selectedItem);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"进入标注编辑时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 检查是否可以执行标注命令
        /// </summary>
        private bool CanExecuteAnnotation()
        {
            // 使用与合并按钮相同的数据源检查是否有选中的记录
            var selectedMergedItems = MergedPlateAnnotationInfos?.Where(x => x.IsSelected).ToList() ?? new List<MergedPlateAnnotationInfoViewModel>();
            return selectedMergedItems.Any();
        }

        /// <summary>
        /// 获取当前选中的项
        /// </summary>
        private PlateAnnotationInfo GetCurrentSelectedItem()
        {
            // 优先使用当前选中的合并项，如果没有则使用第一个选中的合并项
            var selectedMergedItem = CurrentSelectedMergedItem ?? MergedPlateAnnotationInfos?.FirstOrDefault(x => x.IsSelected);
            return selectedMergedItem?.GetPrimaryOriginalData();
        }

        /// <summary>
        /// 获取选中的原始数据（用于合并布局等操作）
        /// </summary>
        private List<PlateAnnotationInfo> GetSelectedOriginalData()
        {
            var selectedMergedItems = MergedPlateAnnotationInfos?.Where(x => x.IsSelected).ToList() ?? new List<MergedPlateAnnotationInfoViewModel>();
            var allSelectedData = new List<PlateAnnotationInfo>();
            
            foreach (var mergedItem in selectedMergedItems)
            {
                allSelectedData.AddRange(mergedItem.GetAllOriginalData());
            }
            
            return allSelectedData;
        }

        /// <summary>
        /// 从合并项中获取布局信息
        /// </summary>
        private LayoutInfo GetLayoutInfoFromMergedItem(MergedPlateAnnotationInfoViewModel mergedItem)
        {
            try
            {
                // 从合并项的主记录中获取布局信息
                var primaryData = mergedItem.GetPrimaryOriginalData();
                if (primaryData?.LayoutInfo != null)
                {
                    // 尝试反序列化布局信息
                    var layoutInfo = JsonConvert.DeserializeObject<LayoutInfo>(primaryData.LayoutInfo);
                    return layoutInfo;
                }
                
                // 如果主记录没有布局信息，尝试从其他记录中获取
                var allData = mergedItem.GetAllOriginalData();
                foreach (var data in allData)
                {
                    if (data?.LayoutInfo != null)
                    {
                        var layoutInfo = JsonConvert.DeserializeObject<LayoutInfo>(data.LayoutInfo);
                        if (layoutInfo != null)
                        {
                            return layoutInfo;
                        }
                    }
                }
                
                return null;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取布局信息失败: {ex.Message}");
                return null;
            }
        }

        private bool CanDxfAnnotate()
        {
            return true;
        }

        /// <summary>
        /// 处理布局信息更新领域事件
        /// </summary>
        /// <param name="layoutInfo">布局信息</param>
        private async void OnLayoutInfoUpdated(LayoutInfo layoutInfo)
        {
            try
            {
                if (layoutInfo?.Merged?.PartLayouts == null || !layoutInfo.Merged.PartLayouts.Any())
                    return;

                // 更新相关的PlateAnnotationInfo记录
                var updatedCount = 0;
                var layoutInfoJson = JsonConvert.SerializeObject(layoutInfo, Formatting.Indented);
                var mergedInfo = string.Join(",", layoutInfo.Merged.PartLayouts.Select(p => p.SheetConsistentNo).ToList());
                
                // 获取所有参与合并的SheetConsistentNo
                var mergedSheetConsistentNos = layoutInfo.Merged.PartLayouts.Select(p => p.SheetConsistentNo).ToHashSet();
                
                System.Diagnostics.Debug.WriteLine($"开始更新合并布局信息，涉及钢板一贯编号: {string.Join(", ", mergedSheetConsistentNos)}");
                
                // 首先从数据库获取所有相关的记录，确保不遗漏任何记录
                var allRecords = await _dataSyncService.GetPlateAnnotationInfosAsync();
                var recordsToUpdate = allRecords.Where(r => mergedSheetConsistentNos.Contains(r.SheetConsistentNo)).ToList();
                
                System.Diagnostics.Debug.WriteLine($"从数据库找到 {recordsToUpdate.Count} 条需要更新的记录");
                
                // 更新数据库中的所有相关记录
                foreach (var record in recordsToUpdate)
                {
                    // 更新数据库记录
                    record.LayoutMean = LayoutMean.MergedLayout;
                    record.LayoutInfo = layoutInfoJson;
                    record.MergedInfo = mergedInfo;
                    
                    // 通过DataSyncService更新数据库
                    await _dataSyncService.UpdateLayoutInfoAsync(record.Id, LayoutMean.MergedLayout, layoutInfoJson);
                    await _dataSyncService.UpdateMergedInfoAsync(record.Id, mergedInfo);
                    
                    updatedCount++;
                    System.Diagnostics.Debug.WriteLine($"已更新数据库记录: {record.SheetConsistentNo}, 处理方式: {LayoutMean.MergedLayout}, 合并信息: {mergedInfo}");
                }
                
                // 更新内存中的记录（如果存在）
                if (PlateAnnotationInfos != null)
                {
                foreach (var partLayout in layoutInfo.Merged.PartLayouts)
                {
                        var targetInfo = PlateAnnotationInfos.FirstOrDefault(p => p.SheetConsistentNo == partLayout.SheetConsistentNo);
                    if (targetInfo != null)
                    {
                            // 更新内存中的布局相关信息
                            targetInfo.OriginalData.LayoutMean = LayoutMean.MergedLayout;
                            targetInfo.OriginalData.LayoutInfo = layoutInfoJson;
                            targetInfo.OriginalData.MergedInfo = mergedInfo;
                            
                            System.Diagnostics.Debug.WriteLine($"已更新内存记录: {partLayout.SheetConsistentNo}, 处理方式: {LayoutMean.MergedLayout}, 合并信息: {mergedInfo}");
                        }
                    }
                }

                // 刷新UI显示
                if (updatedCount > 0)
                {
                    // 重新加载数据以确保UI显示最新状态
                    await LoadProcessSequenceDataAsync();
                    
                    // 刷新合并数据以更新UI状态
                    CreateMergedData();
                    
                    // 重新评估命令状态
                    ExportDocumentsCommand?.RaiseCanExecuteChanged();
                    AnnotationCommand?.RaiseCanExecuteChanged();
                    MergeLayoutCommand?.RaiseCanExecuteChanged();
                    
                    System.Diagnostics.Debug.WriteLine($"成功更新了 {updatedCount} 条布局信息记录，UI已刷新");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"处理布局信息更新领域事件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 处理解除合并布局事件
        /// </summary>
        /// <param name="plateAnnotationInfos">要解除合并的PlateAnnotationInfo列表</param>
        private async void OnUnmergeLayout(List<PlateAnnotationInfo> plateAnnotationInfos)
        {
            try
            {
                if (plateAnnotationInfos == null || !plateAnnotationInfos.Any())
                {
                    System.Diagnostics.Debug.WriteLine("解除合并事件：没有数据需要处理");
                    return;
                }

                System.Diagnostics.Debug.WriteLine($"开始处理解除合并事件，涉及 {plateAnnotationInfos.Count} 条记录");

                // 获取所有需要解除合并的SheetConsistentNo
                var sheetConsistentNos = plateAnnotationInfos.Select(p => p.SheetConsistentNo).ToHashSet();
                
                // 首先从数据库获取所有相关的记录，确保不遗漏任何记录
                var allRecords = await _dataSyncService.GetPlateAnnotationInfosAsync();
                var recordsToUpdate = allRecords.Where(r => sheetConsistentNos.Contains(r.SheetConsistentNo)).ToList();
                
                System.Diagnostics.Debug.WriteLine($"从数据库找到 {recordsToUpdate.Count} 条需要解除合并的记录");

                // 更新数据库中的所有相关记录
                var updatedCount = 0;
                var recordIds = new List<int>();
                foreach (var record in recordsToUpdate)
                {
                    // 更新数据库记录，清除合并信息
                    record.LayoutMean = LayoutMean.Unprocessed;
                    record.LayoutInfo = string.Empty;
                    record.MergedInfo = string.Empty;
                    
                    // 通过DataSyncService更新数据库
                    await _dataSyncService.UpdateLayoutInfoAsync(record.Id, LayoutMean.Unprocessed, string.Empty);
                    await _dataSyncService.UpdateMergedInfoAsync(record.Id, string.Empty);
                    
                    recordIds.Add(record.Id);
                    updatedCount++;
                    System.Diagnostics.Debug.WriteLine($"已清除数据库记录 {record.SheetConsistentNo} 的合并信息");
                }
                
                // 将所有相关图纸的IsAnnotationGenerated设置为False
                if (recordIds.Any())
                {
                    await _dataSyncService.UpdateAnnotationGeneratedStatusAsync(recordIds, false);
                    System.Diagnostics.Debug.WriteLine($"已将 {recordIds.Count} 条记录的IsAnnotationGenerated设置为False");
                }
                
                // 更新内存中的记录（如果存在）
                if (PlateAnnotationInfos != null)
                {
                foreach (var plateAnnotationInfo in plateAnnotationInfos)
                {
                        var targetInfo = PlateAnnotationInfos.FirstOrDefault(p => p.SheetConsistentNo == plateAnnotationInfo.SheetConsistentNo);
                    if (targetInfo != null)
                    {
                            // 清除内存中的合并相关信息，恢复为未处理状态
                            targetInfo.OriginalData.LayoutMean = LayoutMean.Unprocessed;
                            targetInfo.OriginalData.LayoutInfo = string.Empty;
                            targetInfo.OriginalData.MergedInfo = string.Empty;
                            targetInfo.OriginalData.IsAnnotationGenerated = false;
                            
                            System.Diagnostics.Debug.WriteLine($"已清除内存记录 {targetInfo.SheetConsistentNo} 的合并信息，标注状态: False");
                        }
                    }
                }

                // 刷新UI显示
                if (updatedCount > 0)
                {
                    // 重新加载数据以确保UI显示最新状态
                    await LoadProcessSequenceDataAsync();
                    
                    // 刷新合并数据以更新UI状态
                    CreateMergedData();
                    
                    // 重新评估命令状态
                    ExportDocumentsCommand?.RaiseCanExecuteChanged();
                    AnnotationCommand?.RaiseCanExecuteChanged();
                    MergeLayoutCommand?.RaiseCanExecuteChanged();
                    
                    System.Diagnostics.Debug.WriteLine($"成功解除了 {updatedCount} 条记录的合并状态，UI已刷新");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"处理解除合并布局事件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 加载测试数据用于布局功能验证
        /// </summary>
        private void LoadTestData()
        {
            try
            {
                var testData = TestDataGenerator.GenerateLayoutTestData();
                var viewModels = testData.Select(info => new PlateAnnotationInfoViewModel(info)).ToList();
                PlateAnnotationInfos = new ObservableCollection<PlateAnnotationInfoViewModel>(viewModels);
                FilteredPlateAnnotationInfos = TestDataGenerator.GenerateLayoutTestViewModels();

                System.Diagnostics.Debug.WriteLine($"已加载 {testData.Count} 条测试数据用于布局功能验证");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载测试数据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 加载合并测试数据
        /// </summary>
        private void LoadMergeTestData()
        {
            try
            {
                var testData = MergeTestDataGenerator.GenerateMergeTestData();
                var viewModels = testData.Select(info => new PlateAnnotationInfoViewModel(info)).ToList();
                PlateAnnotationInfos = new ObservableCollection<PlateAnnotationInfoViewModel>(viewModels);
                FilteredPlateAnnotationInfos = MergeTestDataGenerator.GenerateMergeTestViewModels();

                System.Diagnostics.Debug.WriteLine($"已加载 {testData.Count} 条合并测试数据");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载合并测试数据失败: {ex.Message}");
            }
        }
        #endregion

        #region properties

        // KMACS加工信息集合
        private ObservableCollection<KmacsProcessInfoDto> _kmacsProcessInfos = new ObservableCollection<KmacsProcessInfoDto>();
        public ObservableCollection<KmacsProcessInfoDto> KmacsProcessInfos
        {
            get => _kmacsProcessInfos;
            set => SetProperty(ref _kmacsProcessInfos, value);
        }

        // KmacsService
        private readonly KmacsService _kmacsService;

        // AM/CadWin Service
        private readonly AmService _amService = new AmService();
        private readonly CadWinService _cadWinService = new CadWinService();

        // 统一标注信息集合
        private ObservableCollection<PlateAnnotationInfoViewModel> _plateAnnotationInfos = new ObservableCollection<PlateAnnotationInfoViewModel>();
        public ObservableCollection<PlateAnnotationInfoViewModel> PlateAnnotationInfos
        {
            get => _plateAnnotationInfos;
            set => SetProperty(ref _plateAnnotationInfos, value);
        }

        // 刷新命令
        public DelegateCommand RefreshKmacsCommand { get; set; }

        // 多来源加载命令
        public DelegateCommand LoadKmacsCommand { get; set; }
        public DelegateCommand LoadAmCommand { get; set; }
        public DelegateCommand LoadCadWinCommand { get; set; }

        // 工作空间相关命令
        public DelegateCommand RefreshWorkSpaceCommand { get; set; }
        public DelegateCommand EditWorkSpaceCommand { get; set; }

        // 工作空间树控件
        public ObservableCollection<BaseInfoTreeNode> WorkSpaceNodes { get; set; }

        private readonly ShipInfoService _shipInfoService;
        private readonly ILayoutService _layoutService;
        private readonly IWorkSpaceService _workSpaceService;
        private readonly IGlobalConfigService _globalConfigService;
        private readonly DataSyncService _dataSyncService;

        #endregion

        #region INavigationAware Implementation

        public async void OnNavigatedTo(NavigationContext navigationContext)
        {
            // 处理导航参数
            if (navigationContext.Parameters.ContainsKey("BaseInfo"))// 从基础信息视图导航过来
            {
                // 从基础信息视图导航过来时，需要先刷新工作空间，然后加载数据
                await RefreshWorkSpaceAsync();
                return; // 重要：这里需要return，避免重复加载数据
            }

            if (navigationContext.Parameters.ContainsKey("WorkSpaceId"))
            {
                WorkSpaceId = navigationContext.Parameters.GetValue<int>("WorkSpaceId");
                System.Diagnostics.Debug.WriteLine($"导航到ProcessSequenceView，WorkSpaceId: {WorkSpaceId}");
            }

            if (navigationContext.Parameters.ContainsKey("WorkSpaceName"))
            {
                WorkSpaceName = navigationContext.Parameters.GetValue<string>("WorkSpaceName");
                System.Diagnostics.Debug.WriteLine($"导航到ProcessSequenceView，WorkSpaceName: {WorkSpaceName}");
            }

            // 统一的数据加载流程：先查询所有数据，再根据工作空间过滤
            _ = LoadProcessSequenceDataAsync();
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            // 检查是否是同一个工作空间
            if (navigationContext.Parameters.ContainsKey("WorkSpaceId"))
            {
                var incomingWorkSpaceId = navigationContext.Parameters.GetValue<int>("WorkSpaceId");
                return WorkSpaceId == incomingWorkSpaceId;
            }
            return false;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            // 清理资源或保存状态
            System.Diagnostics.Debug.WriteLine($"离开ProcessSequenceView，WorkSpaceId: {WorkSpaceId}");

            // 清理工作空间节点数据
            if (WorkSpaceNodes != null)
            {
                WorkSpaceNodes.Clear();
            }

            // 清理当前工作空间引用，避免状态残留
            if (_workSpaceService != null)
            {
                _workSpaceService.SetCurrentWorkSpace(null);
            }

            // 重置工作空间ID和名称
            WorkSpaceId = 0;
            WorkSpaceName = string.Empty;

            System.Diagnostics.Debug.WriteLine("ProcessSequenceView - 已清理工作空间状态");
        }

        private async void LoadWorkSpaceDataAsync()
        {
            // 直接调用统一的数据加载方法
            await LoadProcessSequenceDataAsync();
        }

        #endregion

    }
}
